package com.chris.easymallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.chris.common.utils.R;
import com.chris.easymallproduct.dto.BrandUpdateStatusDto;
import com.chris.easymallproduct.entity.CategoryBrandRelationEntity;
import com.chris.easymallproduct.service.CategoryBrandRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chris.common.utils.PageUtils;
import com.chris.common.utils.Query;

import com.chris.easymallproduct.dao.BrandDao;
import com.chris.easymallproduct.entity.BrandEntity;
import com.chris.easymallproduct.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

import static com.chris.common.constant.ExceptionMessage.OPERATION_FAILED;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new Query<BrandEntity>().getPageWrapper(params, BrandEntity.class)
        );
        return new PageUtils(page);
    }

    @Override
    public R updateStatus(BrandUpdateStatusDto dto) {
        BrandEntity brandEntity = new BrandEntity();
        BeanUtils.copyProperties(dto, brandEntity);
        return this.updateById(brandEntity) ? R.ok() : R.error(OPERATION_FAILED);
    }

    @Override
    @Transactional
    public void update(BrandEntity brand) {
        this.updateById(brand);

        //同步修改品牌名
        categoryBrandRelationService.update(new UpdateWrapper<CategoryBrandRelationEntity>()
                .lambda()
                .set(CategoryBrandRelationEntity::getBrandName, brand.getName())
                .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId()));

    }

}